<template>
  <div class="harvestContainer">
    <!-- 头部 -->
    <div class="header">
      <div class="title" title="添加收获">Add</div>
    </div>

    <div class="divide"></div>

    <!-- 新增收获 -->
    <AddHarvest :changeRefreshSignal="changeRefreshSignal" />

    <div class="divide"></div>

    <!-- 头部 -->
    <div class="header">
      <div class="title" title="收获列表">HarvestList</div>
    </div>

    <div class="divide"></div>

    <!-- 收获列表 -->
    <HarvestList
      :page="page"
      :pageSize="size"
      :setTotal="setTotal"
      :refreshSignal="refreshSignal"
      :changeRefreshSignal="changeRefreshSignal"
    />

    <!-- 分页栏 -->
    <PaginationBar
      :size="size"
      :page="page"
      :total="total"
      :sizeChange="sizeChange"
      :currentChange="pageChange"
    />
    <div class="divide"></div>
  </div>
</template>

<script lang="tsx" setup>
import { defineComponent, onMounted, ref, watch } from 'vue'
import { useThemeStore, useProjectStore } from '@/features/store/store'
import { storeToRefs } from 'pinia'
import {
  Sort,
  StarFilled,
  Clock,
  Edit,
  DeleteFilled,
  Setting,
  Tools,
  Reading,
  Files,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import styles from './harvest.module.less'
import { getProjectModulesApi } from '@/request/api/module'
import {
  getHarvestPageListApi,
  createHarvestApi,
  updateHarvestApi,
  modifyHarvestModuleApi,
  deleteHarvestApi,
} from '@/request/api/harvest'
import LoadingClass from '@/utils/utilClass/Loading'
import PaginationBar from '@/components/PaginationBar.vue'

// 是否更新数据信号
const refreshSignal = ref<string>('')
// 更新信号
const changeRefreshSignal = () => (refreshSignal.value = new Date() + '')

//
// 新增收获
const AddHarvest = defineComponent({
  props: {
    changeRefreshSignal: { type: Function, defaule: '' },
  },
  setup(props) {
    const { buttonColor } = storeToRefs(useThemeStore())

    // 新增收获
    const addHeight = ref<'120px' | '28px'>('28px')
    const addOverflow = ref<'hidden' | ''>('hidden')
    const extendAddBar = ref<true | false>(false)
    // 切换新增栏
    const toggleAdd = (): void => {
      if (extendAddBar.value) {
        extendAddBar.value = false
        addHeight.value = '28px'
        addOverflow.value = 'hidden'
      } else {
        addHeight.value = '120px'
        addOverflow.value = ''
        setTimeout(() => (extendAddBar.value = true), 180)
      }
    }

    const { projectId } = storeToRefs(useProjectStore())

    // 收获模块id
    const moduleId = ref<string>('')
    // 项目模块列表
    const moduleList = ref<{ id: string; label: string }[]>([])
    // 收获描述
    const description = ref<string>('')

    const ClassLoading = new LoadingClass()

    // 获取项目的模块列表
    const getProjectModules = async (visible: boolean) => {
      if (!visible) return
      ClassLoading.setTips('获取项目模块列表中。。。')
      const res = await getProjectModulesApi(projectId.value)

      if (res.code !== 200) {
        moduleList.value = []
        return ClassLoading.setTips('获取项目模块列表失败！')
      }
      ClassLoading.setTips('获取项目模块列表成功！')

      moduleList.value = res.data.map((item) => {
        return { id: item.id, label: item.name }
      })
    }

    // 创建收获
    const createHarvest = async () => {
      if (description.value.length === 0)
        return ClassLoading.setTips('收获描述不能为空！')

      ClassLoading.loading.value = true
      const res = await createHarvestApi({
        projectId: projectId.value,
        moduleId: moduleId.value,
        description: description.value,
      })
      ClassLoading.loading.value = false

      if (res.code !== 200) return ClassLoading.setTips('新增收获失败！')

      ClassLoading.setTips('新增收获成功！')
      moduleId.value = ''
      description.value = ''
      props.changeRefreshSignal()
    }

    return () => (
      <div
        class={styles.addHarvest}
        style={{ height: addHeight.value, overflow: addOverflow.value }}
      >
        <div class={styles.tipsTxt} v-show={!extendAddBar.value}>
          新增收获
        </div>

        <div class={styles.addPart} v-show={extendAddBar.value}>
          <div class={styles.module}>
            <div class={styles.label}>收获所属项目模块：</div>
            <div>
              <el-select
                v-model={moduleId.value}
                placeholder="Select harvest module"
                onVisibleChange={getProjectModules}
              >
                {moduleList.value.map((item) => {
                  return (
                    <el-option
                      key={item.id}
                      label={item.label}
                      value={item.id}
                    />
                  )
                })}
              </el-select>
            </div>

            <div>
              <el-button
                type="primary"
                plain
                color={buttonColor.value}
                loading={ClassLoading.loading.value}
                onClick={createHarvest}
              >
                新增
              </el-button>
              <div class={styles.tips}>{ClassLoading.resultTips.value}</div>
            </div>
          </div>

          <div class={styles.description}>
            <div class={styles.label}>
              <el-icon size="12" color="red" title="必填项">
                <StarFilled />
              </el-icon>
              收获描述：
            </div>

            <div>
              <el-input
                v-model={description.value}
                placeholder="Please input project description"
                type="textarea"
                rows={3}
                show-word-limit
                maxlength="300"
              />
            </div>
          </div>
        </div>

        <div class={styles.toggle}>
          <div onClick={toggleAdd}>
            <el-icon size="24" color={buttonColor.value}>
              <Sort />
            </el-icon>
          </div>
        </div>
      </div>
    )
  },
})

// 分页栏相关信息
const size = ref<number>(12)
const page = ref<number>(1)
const total = ref<number>(0)
const pageChange = (p: number) => {
  page.value = p
  changeRefreshSignal()
}
const sizeChange = (s: number) => {
  size.value = s
  changeRefreshSignal()
}
const setTotal = (t: number) => (total.value = t)

//
// 收获列表
const HarvestList = defineComponent({
  props: {
    page: { type: Number, defaule: '' },
    pageSize: { type: Number, defaule: '' },
    setTotal: { type: Function, defaule: '' },
    refreshSignal: { type: String, defaule: '' },
    changeRefreshSignal: { type: Function, defaule: '' },
  },
  setup(props) {
    const { buttonColor } = storeToRefs(useThemeStore())
    const { projectId } = storeToRefs(useProjectStore())

    onMounted(() => {
      getHarvestPageList()
    })

    watch(
      () => projectId.value,
      () => getHarvestPageList()
    )
    watch(
      () => props.refreshSignal,
      () => getHarvestPageList()
    )

    // 当前正在操作的卡片id
    const settingCardId = ref<string>('')
    const setSettingCardId = (id: string) => (settingCardId.value = id)

    // 收获列表
    const harvestList = ref<getHarvestResultItf[]>([])
    // 分页获取项目收获
    const getHarvestPageList = async () => {
      const res = await getHarvestPageListApi({
        projectId: projectId.value,
        page: props.page,
        pageSize: props.pageSize,
      })

      if (res.code !== 200) return (harvestList.value = [])
      props.setTotal(res.data.total)
      harvestList.value = res.data.records
    }

    // 项目信息展示卡片
    const HarvestInfo = defineComponent({
      props: {
        id: { type: String, default: '' },
        createTime: { type: String, default: '' },
        description: { type: String, default: '' },
        moduleName: { type: String, default: '' },
        updateTime: { type: String, default: '' },
        currentId: { type: String, default: '' },
        setCurrentId: { type: Function, default: '' },
        changeRefreshSignal: { type: Function, default: () => '' },
      },
      setup(props) {
        const { buttonColor } = storeToRefs(useThemeStore())
        const { projectId } = storeToRefs(useProjectStore())

        const deleteHarvest = async () => {
          const res = await deleteHarvestApi(props.id)
          console.log(res)
          if (res.code !== 200) return ElMessage.error('删除收获失败！')
          props.changeRefreshSignal()
        }

        // 打开阅读窗口
        const openReadingWindow = () =>
          (window as any).readingWindow.openWindow({
            projectId: projectId.value,
            harvestId: props.id,
            token: window.localStorage.getItem('token'),
            type: 'readWindow',
          })

        return () => (
          <div class={styles.harvestInfo}>
            <div class={styles.info}>
              <div class={styles.time}>
                <el-icon
                  size="22"
                  color={buttonColor.value}
                  title={'创建时间：' + props.createTime}
                >
                  <Clock />
                </el-icon>
                <div> {props.createTime.split(' ')[0]}</div>
                <el-icon
                  size="22"
                  color={buttonColor.value}
                  title={'最近更新时间：' + props.createTime}
                >
                  <Edit />
                </el-icon>
                <div>{props.updateTime.split(' ')[0]}</div>
                <el-icon
                  size="22"
                  color={buttonColor.value}
                  title="所属项目模块"
                >
                  <Files />
                </el-icon>
                <div>{props.moduleName}</div>
              </div>

              <div class={styles.setting}>
                <div v-show={props.id !== props.currentId}>
                  <el-popconfirm
                    confirm-button-text="确认"
                    cancel-button-text="取消"
                    title="确定删除吗？"
                    onConfirm={deleteHarvest}
                    v-slots={{
                      reference: () => (
                        <el-icon
                          size="24"
                          color={buttonColor.value}
                          title="删除"
                        >
                          <DeleteFilled />
                        </el-icon>
                      ),
                    }}
                  ></el-popconfirm>
                </div>
                <div>
                  <el-icon
                    size="24"
                    color={buttonColor.value}
                    title="阅读"
                    onClick={openReadingWindow}
                  >
                    <Reading />
                  </el-icon>
                </div>
                <div v-show={props.id !== props.currentId}>
                  <el-icon
                    size="24"
                    color={buttonColor.value}
                    title="设置"
                    onClick={() => props.setCurrentId(props.id)}
                  >
                    <Setting />
                  </el-icon>
                </div>
                <div v-show={props.id === props.currentId}>
                  <el-icon
                    size="24"
                    color={buttonColor.value}
                    title="设置"
                    onClick={() => props.setCurrentId('')}
                  >
                    <Tools />
                  </el-icon>
                </div>
              </div>
            </div>

            {/* 收获描述 */}
            <div class={styles.description} title={props.description}>
              {props.description}
            </div>
          </div>
        )
      },
    })

    // 修改模块
    const ModifyModule = defineComponent({
      props: {
        id: { type: String, defaule: '' },
        moduleId: { type: String, defaule: '' },
        changeRefreshSignal: { type: Function, default: () => '' },
      },
      setup(props) {
        const { buttonColor } = storeToRefs(useThemeStore())
        const { projectId } = storeToRefs(useProjectStore())

        onMounted(() => {
          getProjectModules()
        })

        // 收获模块id
        const moduleId = ref<string>(props.moduleId)
        // 项目模块列表
        const moduleList = ref<{ id: string; label: string }[]>([])
        const ClassLoading = new LoadingClass()

        // 获取项目的模块列表
        const getProjectModules = async () => {
          ClassLoading.setTips('获取项目模块列表中。。。')
          const res = await getProjectModulesApi(projectId.value)

          if (res.code !== 200) {
            moduleList.value = []
            return ClassLoading.setTips('获取项目模块列表失败！')
          }
          ClassLoading.setTips('获取项目模块列表成功！')

          moduleList.value = res.data.map((item) => {
            return { id: item.id, label: item.name }
          })

          // moduleId.value = props.moduleId
        }

        // 修改模块
        const modifyHarvestModule = async () => {
          ClassLoading.loading.value = true
          const res = await modifyHarvestModuleApi({
            id: props.id,
            moduleId: moduleId.value,
          })
          ClassLoading.loading.value = false

          if (res.code !== 200) return ClassLoading.setTips('修改模块失败！')
          ClassLoading.setTips('修改模块成功！')
          props.changeRefreshSignal()
        }

        return () => (
          <div class={styles.modifyModule}>
            <div class={styles.label}>修改收获所属模块：</div>
            <el-select
              v-model={moduleId.value}
              placeholder="Select harvest module"
              clearable
            >
              {moduleList.value.map((item) => {
                return (
                  <el-option key={item.id} label={item.label} value={item.id} />
                )
              })}
            </el-select>
            &nbsp;&nbsp;
            <el-button
              plain
              size="small"
              color={buttonColor.value}
              loading={ClassLoading.loading.value}
              onClick={modifyHarvestModule}
            >
              更新
            </el-button>
            <div class={styles.tips}>{ClassLoading.resultTips.value}</div>
          </div>
        )
      },
    })

    // 更新收获描述
    const UpdateDesc = defineComponent({
      props: {
        id: { type: String, default: '' },
        description: { type: String, default: '' },

        changeRefreshSignal: { type: Function, defaule: '' },
      },
      setup(props) {
        const description = ref<string>(props.description)

        const ClassLoading = new LoadingClass()

        //更新收获描述
        const updateHarvest = async () => {
          if (description.value == '')
            return ClassLoading.setTips('收获描述不能为空！')

          ClassLoading.loading.value = true
          const res = await updateHarvestApi({
            id: props.id,
            description: description.value,
          })
          ClassLoading.loading.value = false

          if (res.code !== 200) return ClassLoading.setTips('更新描述失败！')
          ClassLoading.setTips('更新描述成功！')
          props.changeRefreshSignal()
        }

        return () => (
          <div class={styles.updateDescription}>
            <div class={styles.label}>
              <div>更新收获描述：</div>

              <div class={styles.btn}>
                <div class={styles.tips}>{ClassLoading.resultTips.value}</div>
                <el-button
                  plain
                  size="small"
                  color={buttonColor.value}
                  loading={ClassLoading.loading.value}
                  onClick={updateHarvest}
                >
                  更新
                </el-button>
              </div>
            </div>

            <div class={styles.updateInput}>
              <el-input
                v-model={description.value}
                placeholder="Please input project description"
                type="textarea"
                rows={3}
                show-word-limit
                maxlength="300"
              />
            </div>
          </div>
        )
      },
    })

    return () => (
      <div class={styles.harvestList}>
        {harvestList.value?.map((item) => {
          return (
            <div
              class={styles.card}
              key={item.id}
              id={settingCardId.value === item.id ? styles.settingCard : ''}
            >
              {/* 收获信息 */}
              <HarvestInfo
                id={item.id}
                createTime={item.createTime}
                description={item.description}
                moduleName={item.moduleName}
                updateTime={item.updateTime}
                currentId={settingCardId.value}
                setCurrentId={setSettingCardId}
                changeRefreshSignal={props.changeRefreshSignal}
              />

              <div
                class={styles.divide}
                v-show={settingCardId.value === item.id}
              ></div>

              {/* 修改模块 */}
              <ModifyModule
                v-show={settingCardId.value === item.id}
                id={item.id}
                moduleId={item.moduleId}
                changeRefreshSignal={props.changeRefreshSignal}
              />

              <div
                class={styles.divide}
                v-show={settingCardId.value === item.id}
              ></div>

              {/* 更新描述 */}
              <UpdateDesc
                v-show={settingCardId.value === item.id}
                id={item.id}
                description={item.description}
                changeRefreshSignal={props.changeRefreshSignal}
              />

              <div
                class={styles.divide}
                v-show={settingCardId.value === item.id}
              ></div>
            </div>
          )
        })}
      </div>
    )
  },
})
</script>

<style lang="less" scoped>
@fontstyle: comic Sans MS, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
  Oxygen, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;

.harvestContainer {
  width: calc(100% - 24px);
  min-height: 100%;
  padding: 12px;

  > .header {
    width: 100%;
    transition: 0.2s;

    > .title {
      font-family: @fontstyle;
      font-size: 18px;
      font-weight: bold;
      color: var(--theme-active-label);
      user-select: none;
    }
  }

  > .divide {
    height: 2px;
    width: 100%;
    background-color: var(--theme-header);
    margin-top: 10px;
    margin-bottom: 10px;
  }
}
</style>
